import os
import re
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import webbrowser  # 新增模块用于网页跳转

class FileRenamerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("【文件批量重命名工具 v1.1 - 咖啡续命又一天】")  # 修改标题

        # 新增超链接按钮
        self.hyperlink = tk.Label(root, text="咖啡续命又一天", fg="blue", cursor="hand2")
        self.hyperlink.grid(row=5, column=0, columnspan=3, padx=5, pady=5)
        self.hyperlink.bind("<Button-1>", lambda e: self.open_url("https://blog.csdn.net/qq_41964263"))  # 替换为你自己的网址

        # 目录选择
        tk.Label(root, text="目标目录:").grid(row=0, column=0, padx=5, pady=5, sticky="e")
        self.dir_entry = tk.Entry(root, width=50)
        self.dir_entry.grid(row=0, column=1, padx=5, pady=5)
        self.dir_entry.insert(0, "请选择目标文件夹")  # 默认提示
        self.dir_entry.config(fg='gray')  # 提示文字颜色
        self.dir_entry.bind("<FocusIn>", lambda e: self.on_entry_focus_in(e, self.dir_entry, "请选择目标文件夹"))
        self.dir_entry.bind("<FocusOut>", lambda e: self.on_entry_focus_out(e, self.dir_entry, "请选择目标文件夹"))
        tk.Button(root, text="浏览...", command=self.select_directory).grid(row=0, column=2, padx=5, pady=5)

        # 正则表达式输入
        tk.Label(root, text="正则表达式:").grid(row=1, column=0, padx=5, pady=5, sticky="e")
        self.pattern_entry = tk.Entry(root, width=50)
        self.pattern_entry.grid(row=1, column=1, padx=5, pady=5)
        self.pattern_entry.insert(0, r"^old_")  # 提示文字
        self.pattern_entry.config(fg='gray')  # 设置提示文字颜色为灰色
        self.pattern_entry.bind("<FocusIn>", lambda e: self.on_entry_focus_in(e, self.pattern_entry, r"^old_"))
        self.pattern_entry.bind("<FocusOut>", lambda e: self.on_entry_focus_out(e, self.pattern_entry, r"^old_"))

        # 替换内容输入
        tk.Label(root, text="替换为:").grid(row=2, column=0, padx=5, pady=5, sticky="e")
        self.replacement_entry = tk.Entry(root, width=50)
        self.replacement_entry.grid(row=2, column=1, padx=5, pady=5)
        self.replacement_entry.insert(0, "new_")  # 提示文字
        self.replacement_entry.config(fg='gray')  # 设置提示文字颜色为灰色
        self.replacement_entry.bind("<FocusIn>", lambda e: self.on_entry_focus_in(e, self.replacement_entry, "new_"))
        self.replacement_entry.bind("<FocusOut>", lambda e: self.on_entry_focus_out(e, self.replacement_entry, "new_"))

        # 操作按钮
        tk.Button(root, text="预览修改", command=self.preview_rename).grid(row=3, column=1, padx=5, pady=5, sticky="w")
        tk.Button(root, text="执行重命名", command=self.rename_files).grid(row=3, column=1, padx=5, pady=5, sticky="e")

        # 操作日志
        self.log_area = scrolledtext.ScrolledText(root, height=10, wrap=tk.WORD)
        self.log_area.grid(row=4, column=0, columnspan=3, padx=5, pady=5, sticky="nsew")

    def on_entry_focus_in(self, event, entry, placeholder):
        if entry.get() == placeholder:
            entry.delete(0, tk.END)
            entry.config(fg='black')  # 用户输入时使用黑色

    def on_entry_focus_out(self, event, entry, placeholder):
        if entry.get() == '':
            entry.insert(0, placeholder)
            entry.config(fg='gray')  # 如果为空，恢复提示文字

    def select_directory(self):
        dir_path = filedialog.askdirectory()
        if dir_path:
            self.dir_entry.delete(0, tk.END)
            self.dir_entry.insert(0, dir_path)
            self.dir_entry.config(fg='black')  # 用户输入时使用黑色

    def preview_rename(self):
        directory = self.dir_entry.get()
        pattern = self.pattern_entry.get()
        replacement = self.replacement_entry.get()

        if not os.path.isdir(directory):
            messagebox.showerror("错误", "目标目录不存在！")
            return

        try:
            self.log_area.delete(1.0, tk.END)
            for filename in os.listdir(directory):
                new_name = re.sub(pattern, replacement, filename)
                if new_name != filename:
                    self.log_area.insert(tk.END, f"{filename} → {new_name}\n")
        except re.error as e:
            messagebox.showerror("正则表达式错误", str(e))

    def rename_files(self):
        directory = self.dir_entry.get()
        pattern = self.pattern_entry.get()
        replacement = self.replacement_entry.get()

        if not os.path.isdir(directory):
            messagebox.showerror("错误", "目标目录不存在！")
            return

        try:
            count = 0
            for filename in os.listdir(directory):
                new_name = re.sub(pattern, replacement, filename)
                if new_name != filename:
                    src_path = os.path.join(directory, filename)
                    dst_path = os.path.join(directory, new_name)
                    os.rename(src_path, dst_path)
                    self.log_area.insert(tk.END, f"重命名: {filename} → {new_name}\n")
                    count += 1
            messagebox.showinfo("完成", f"成功重命名 {count} 个文件！")
        except re.error as e:
            messagebox.showerror("正则表达式错误", str(e))
        except Exception as e:
            messagebox.showerror("错误", str(e))

    def open_url(self, url):
        """打开指定网页"""
        try:
            webbrowser.open(url)
        except Exception as e:
            messagebox.showerror("错误", f"无法打开网页：{str(e)}")

if __name__ == "__main__":
    root = tk.Tk()
    app = FileRenamerApp(root)
    root.mainloop()